import React, { useState, useRef, useEffect, Fragment } from 'react';
import * as echarts from 'echarts';
import styles from "./index.module.scss";
import './EchartsLine.scss'
import { parseTime } from '@/utils';
import { parseAmount, parsePercentage, parseInteger } from "@/utils/index"
import { useIsMobile } from '@/hooks/useIsMobile'
import iconDownArrow from "@/assets/image/icon-down-arrow.png"
export interface EchartsProps {
    width?: string,
    height?: string,
    xAxis: string[],
    seriesData: number[],
    title?: string,
    tooltip?: any
}

const echartsOption: any = {
    color: '#3E99FF',
    title: {
        text: '实收金额',
        textStyle: {
            color: '#999999',
            fontSize: '11px',
            fontWeight: 400
        }
    },
    tooltip: {
        trigger: 'axis',
        extraCssText: 'background: rgba(34, 34, 34, 0.7); border-radius: 4px;border:none;',
        formatter: (params: any) => {
            const { timeStr, echartTitle, value } = params[0].data
            const amountTitles = ['销售额', '实收金额', '毛利额', '成本金额', '客单价']
            const percentageTitles = ['毛利率']
            const integerTitles = ['订单量']
            let countNum = value
            if (amountTitles.some(item => echartTitle.includes(item))) {
                countNum = parseAmount(value)
            } else if (percentageTitles.some(item => echartTitle.includes(item))) {
                countNum = parsePercentage(value)
            }
            else if (integerTitles.some(item => echartTitle.includes(item))) {
                countNum = parseInteger(value)
            }

            return `<div className="tooltip-block">
                <div style="height: 18px;font-size: 13px;color: #DDDDDD;line-height: 18px;">${timeStr}</div>
                <div className="count-block">
                    <span style="height: 18px;font-size: 13px;color: #FFFFFF;line-height: 18px;">${echartTitle}：</span>
                    <span style="height: 18px;font-weight: 500;font-size: 13px;color: #FFFFFF;line-height: 18px;">${countNum}</span>
                </div>
            </div>`
        }
    },
    // dataZoom: [
    //     {
    //         type: 'inside',
    //         xAxisIndex: [0],
    //     }
    // ],
    xAxis: {
        type: 'category',
        data: [],
        boundaryGap: false,
        axisTick: {//坐标轴刻度与标签对齐
            alignWithLabel: true
        },
        axisLabel: {
            // width:10,
            // overflow:"break",
            hideOverlap: true,
            show: true, // 显示坐标轴标签
            interval: 0,// 设置X轴刻度标签的间隔为2，即每隔两个标签显示一次
            fontSize: 10,
            margin: 8,
            formatter: function (value: any, index: number) {
                let remainder = index % 4;

                if (value.indexOf(":") > -1) {
                    remainder = index % 1;
                }
                if (remainder === 0) {
                    return value
                } else {
                    return ''
                }
            }
            // rotate:60
        }
    },
    yAxis: {
        type: 'value',
        minInterval: 0,
        axisLabel: {
            // inside:true    // 刻度标签是否朝内
            formatter: function (value: any) {
                if (value.toString().length < 4) {
                    return value
                }

                // if (value.toString().length === 4) {
                //     return (value / 10000).toFixed(1) + 'w'
                // }

                if (value.toString().length > 4 && value.toString().length < 8) {
                    return (value / 10000).toFixed(1) + 'w'
                }
                if (value.toString().length >= 8) {
                    return (value / 10000000).toFixed(1) + 'kw'
                }
                return value
            },
        },
    },
    series: [
        {
            data: [],
            type: 'line',
            symbol: "none",
            smooth: true,
            areaStyle: {
                color: new echarts.graphic.LinearGradient( // 设置渐变色
                    0, 0, 0, 1,
                    [{
                        offset: 0,
                        color: '#7EB8FF'
                    },
                    {
                        offset: 1,
                        color: '#FFFFFF'
                    }
                    ]
                )
            }
        }
    ],
    grid: [
        { show: false, z: 0, left: '5%', top: 30, right: '5%', bootom: 20, height: 0 }
    ]
};

const cropHeight = (e: string | number, h: number): string => {
    if (typeof e === 'number') return `${e - h}px`
    let v = Number(e.replace('px', ''))
    return `${v - h}px`
}

const formatterAxisLabel = (xAxis: string[]) => {
    if (!xAxis) return []
    if (!xAxis.length) return []
    return xAxis.map((item: any) => {
        if (item.indexOf("-") > -1) {
            const idx = item.indexOf("-")
            return item.slice(idx + 1)
        }
        return item
    })
}

// 处理Y轴数据（防止太宽）
const evalScaleY = (e: any[], isMobile?: boolean) => {
    if (!e.length) return "5%"

    const integerMax = String(Math.max(...e)).split('.')[0]

    let formatYUnityStr: number = 0
    if (integerMax.toString().length < 4) {
        formatYUnityStr = Number(integerMax) > 500 ? integerMax.toString().length + 1 : integerMax.toString().length
    }

    if (integerMax.toString().length === 4) {
        formatYUnityStr = integerMax.length
    }

    if (integerMax.toString().length > 4 && integerMax.toString().length < 8) {
        formatYUnityStr = ((Number(integerMax) / 10000).toFixed(1) + 'w').length
    }

    if (integerMax.toString().length >= 8) {
        formatYUnityStr = ((Number(integerMax) / 10000000).toFixed(1) + 'kw').length - 1
    }

    if (formatYUnityStr < 3) {
        return !isMobile ? "3%" : "8%"
    }

    return formatYUnityStr * 10 + 'px'
}

// 设置X轴展示内容文字间距
const xAxisAxisLabelFormatter = (dateType: number, isMobile: boolean, xAxis: any[]) => {
    if (dateType === 1 || dateType === 2) {
        return function (value: any, index: number) {
            let remainder = isMobile ? index % 2 : index % 1;

            if (remainder === 0) {
                return value
            } else {
                return ''
            }
        }
    }
    if (dateType === 3) {
        return function (value: any, index: number) {
            return value
        }
    }
    if (dateType === 4) {
        return function (value: any, index: number) {
            let remainder = index % 3;

            if (remainder === 0) {
                return value
            } else {
                return ''
            }
        }
    }
    if (dateType === 5) {
        return function (value: any, index: number) {
            let remainder = index % 6;
            // 判断是日期还是小时
            if (value.indexOf(":") > -1) {
                remainder = isMobile ? index % 2 : index % 1;
            } else {
                if (xAxis.length <= 30) {
                    remainder = isMobile ? index % 2 : index % 1;
                } else {
                    remainder = index % 6;
                }
            }

            if (remainder === 0) {
                return value
            } else {
                return ''
            }
        }
    }
}

const EchartsLine: React.FC<EchartsProps> = (props) => {
    const isMobile = useIsMobile()
    const w = props.width || '100%'
    const h = !isMobile ? '320px' : props.height || '200px'

    echartsOption.xAxis.data = formatterAxisLabel(props.xAxis)
    echartsOption.series[0].data = props.seriesData && props.seriesData.map((value, index) => {
        let timeStr = props.xAxis[index]

        if (props?.tooltip?.dateType === 1) {
            timeStr = parseTime(new Date(), '{y}-{m}-{d}') + ' ' + props.xAxis[index]
        }
        if (props?.tooltip?.dateType === 2) {

            var today = new Date(); // 获取今天的日期
            var yesterday = new Date(today); // 通过复制今天的日期创建一个新的日期对象
            yesterday.setDate(today.getDate() - 1); // 将新日期对象的日期减去一天

            timeStr = parseTime(yesterday, '{y}-{m}-{d}') + ' ' + props.xAxis[index]
        }
        return {
            echartTitle: props.title,
            value,
            timeStr
        }
    })
    
    if(props.seriesData && props.seriesData.length){
        echartsOption.grid[0].height = cropHeight(h, 60)
        echartsOption.series[0].symbol = props.seriesData && props.seriesData.length === 1 ? 'emptyCircle' : 'none'
        echartsOption.grid[0].left = evalScaleY(props.seriesData, isMobile)
        props.title && (echartsOption.title.text = props.title)
    }

    const [collapse, setCollapse] = useState<boolean>(true)
    // 收起，展开趋势图
    const toogleTrendChart = () => {
        setCollapse(!collapse)
    }

    const mycanvas = useRef<any>(null)
    // 获取dom 设置图像
    useEffect(() => {
        if (!isMobile) {
            echartsOption.grid[0].right = "1.5%"
            echartsOption.title.textStyle.fontSize = "12px"
        }

        const chartDom = document.getElementById('mycanvas')
        const myChart = echarts.init(chartDom)
        mycanvas.current = myChart
        setTimeout(() => {
            echartsOption && myChart.setOption(echartsOption)
        }, 0)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    useEffect(() => {
        const integerKeyName = ["订单量"]

        if (props.title && integerKeyName.indexOf(props.title) > -1) {
            echartsOption.yAxis.minInterval = 1
        } else {
            echartsOption.yAxis.minInterval = 0
        }
        echartsOption.xAxis.axisLabel.formatter = xAxisAxisLabelFormatter(props.tooltip.dateType, isMobile, echartsOption.xAxis.data)

        echartsOption && mycanvas.current.setOption(echartsOption)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props.xAxis, props.seriesData])

    return (
        <Fragment>
            <div className={styles['echart-line-wrapper']}>
                <div ref={mycanvas} style={{ width: w, height: h }} id="mycanvas" className={`${collapse ? '' : styles['slide-hide-chart']}`}></div>
                <div className={styles['put-away']} onClick={() => { toogleTrendChart() }}>
                    <span className='put-away-name'>{collapse ? '收起' : '展开'}趋势图</span>
                    <img className={`${styles['icon-arrow']} ${collapse ? styles['expand-arrow'] : ''}`} src={iconDownArrow} alt="" />
                </div>
            </div>
        </Fragment>
    )
}

export default EchartsLine
